<template>
  <div>
    <div class="top"><strong>首页</strong> > 用户管理 > 用户列表</div>
    <el-card class="card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="querryinfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6"
          ><div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible = true"
              >添加用户</el-button
            >
          </div></el-col
        >
      </el-row>
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <!-- 获取该行数据 数据读取使用scope.row -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userchange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope ="vog">
            <el-button type="primary" icon="el-icon-edit" @click="bott(vog.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="remove(vog.row.id)"></el-button>
            <el-tooltip
              effect="dark"
              content="配置角色"
              placement="top-end"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" @click="hos(vog.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querryinfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="querryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
        <!-- :page-size 每页显示的条数
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      监听pagenum和pagesize改变的事件
       -->
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addlogclose" >
      <!-- 内容主体区 -->
      <el-form
        :model="addForm"
        :rules="addform"
        ref="addFromRef"
        label-width="90px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="logb"
          >确 定</el-button>
      </span>
    </el-dialog>
       <!-- 修改用户的对话框 -->
    <el-dialog
    title="修改用户"
    :visible.sync="pott"
    width="60%"
    @close="addlogclose"
  >
      <el-form
      :model="editform"
      label-width="90px"
      :rules="addform"
      ref="addFromRef"
      >
       <el-form-item label="用户名" prop="username" >
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="pott = false">取 消</el-button>
    <el-button type="primary" @click="hoy">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="分配角色"
  :visible.sync="diag"
  width="50%"
  @close='gody'
  >
  <div>当前的用户名：{{hoss.username}}</div>
  <div>当前的角色：{{hoss.role_name}}</div>
  <div>分配的角色：
    <el-select v-model="setid" placeholder="请选择">
    <el-option
      v-for="item in roleslist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="diag = false">取 消</el-button>
    <el-button type="primary" @click="ldo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  naem: 'user',
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.querryinfo,
      })
      //console.log(res)
      this.userlist = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(mp) {
      this.querryinfo.pagesize = mp
      this.getUserList()
    },
    handleCurrentChange(mk) {
      this.querryinfo.pagenum = mk
      this.getUserList()
    },
 //用户状态控制
    async userchange(ol) {
      //console.log(ol);
      const { data: res } = await this.$http.put(
        `users/${ol.id}/state/${ol.mg_state}`
      )
      //console.log(res);
      if (res.meta.status !== 200) {
        ol.mg_state = !ol.mg_state
        return this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
      }
    },
    addlogclose(){
        this.$refs.addFromRef.resetFields()   
        },
     //表单预校验   
    logb(){
  this.$refs.addFromRef.validate(async valid => {
            console.log(valid);
              if(!valid) return;
           const{data:res} =  await this.$http.post('users',this.addForm
              )
              if(res.meta.status!=201){
                  this.$message.error('添加用户失败')
              }else{
                  this.$message.success(res.meta.msg)
                  this.dialogVisible = false
                  //重新获取数据列表
                  this.getUserList()
              }
                     
      })
    },
    //获取用户id并保存至editform
    async bott(id){
      console.log(id);
       const{data:res}= await this.$http.get('users/'+id,)
       console.log(res);
        if(res.meta.status!==200){
             return this.$message.error('查询用户失败')
        }
               this.editform = res.data
                this.pott = true
    },
    //点击确认后，将数据提交至后台
    hoy(){
         this.$refs.addFromRef.validate(async valid => {
            console.log(valid);
               if(!valid) return;
           const{data:res} =  await this.$http.put(`users/${this.editform.id}`,this.editform
              )
              console.log(res);
              if(res.meta.status!==200){
                  this.$message.error(res.meta.msg)
              }
               this.$message.success(res.meta.msg)
                  this.pott = false
                  //重新获取数据列表
                  this.getUserList()
              
                     
      })
    },
   async remove(id){
         const bug=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        console.log(bug);
        //成功时是confirm
        //取消是cancel
         if(bug!=='confirm'){
            this.$message.info('已取消删除')
         }else{
          const{data:res}=await this.$http.delete(`users/${id}`)
          if(res.meta.status!==200){
             return this.$message.error('删除用户失败')
          }
          this.$message.success('删除成功')
          this.getUserList()}
    },
      async hos(t){
         this.hoss=t
          const {data:res}=await this.$http.get('roles')
         if(res.meta.status!==200){
           return this.$messgae.error(res.meta.msg)
         }
             this.roleslist=res.data
           console.log(this.roleslist);
         this.diag=true
       },
      async ldo(){
         if(!this.setid){
          return this.$message.error('请输入正确的角色')
         }else{
         const{data:res}  =await this.$http.put(`users/${this.hoss.id}/role`,{
             rid:this.setid
           })
           if(res.meta.status!==200){
             return this.$message.error(res.meta.msg)
           }
             this.$message.success(res.meta.msg)
              this.diag = false
             this.getUserList()
             
          
         }
       },
       gody(){
         this.hoss={},
         this.setid=''
       }
    
  },
  
  data() {
      //对邮箱和手机号码的规则进行自定义组件验证
      var checkemail =(rule,value,cb)=>{
           const regemail = /^\w+@\w+(\.\w+)+$/
           if(regemail.test(value)){
               return cb()
           }
           cb(new Error('请输入合法的邮箱'))

      }
      var checkphone =(rule,value,cb)=>{
           const regemail = /^1[34578]\d{9}$/
           if(regemail.test(value)){
               return cb()
           }
           cb(new Error('请输入合法的手机号码'))

      }
    return {
      setid:'',
      roleslist:[],
      hoss:{},
      querryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
        daig:false,
      },
      userlist: [],
      total: 0,
      // 控制对话框的显示与否
      dialogVisible: false,
      pott:false,
      diag:false,
      addForm:{
          username:'',
          password:'',
          email:'',
          mobile:''
      },
       editform:{
          username:'',
          email:'',
          mobile:''
       },
      addform: {
        username: [
          {
            required: true,
            messgae: '请输入用户名',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            messgae: '请输入密码',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          {
            required: true,
            messgae: '请输入邮箱地址',
            trigger: 'blur',
          },
          {
           validator: checkemail,
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            messgae: '请输入手机号码',
            trigger: 'blur',
          },
          {
            
            validator: checkphone,
            trigger: 'blur',
          },
        ],
      },
    }
  },
}
</script>

<style lang="less" scoped>
.top {
  margin-left: 20px;
  margin-top: 25px;
  font-size: 14px;
}
.card {
  margin: 26px 10px 0px 10px;
  .el-table {
    margin: 10px 20px 0px 0px;
    font-size: 14px;
  }
}
</style>